package com.qf.book.dao.impl;

import com.qf.book.dao.UserDao;
import com.qf.book.domain.User;
import com.qf.book.util.DBUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDaoImpl implements UserDao {
    @Override
    public User select(String username, String password) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            connection = DBUtils.getConnection();
            //String sql = "select * from where username = ? and password = ?";
            //String sql = "SECECT * FROM USER WHERE username = ? AND PASSWORD = ?;";
            String sql = "SELECT * FROM `user` WHERE username = ? AND PASSWORD = ?;";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, username);
            preparedStatement.setString(2, password);
            resultSet = preparedStatement.executeQuery();
            User user = null;
            if (resultSet.next()) {
                int id = resultSet.getInt("id");
                String username1 = resultSet.getString("username");
                String password1 = resultSet.getString("password");
                String realname = resultSet.getString("realname");
                String email = resultSet.getString("email");
                String gender = resultSet.getString("gender");
                int flag = resultSet.getInt("flag");
                int role = resultSet.getInt("role");
                //封装用户
                user = new User(id, username1, password1, realname, email, gender, flag, role);
            }
            return user;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DBUtils.closeAll(resultSet, preparedStatement, connection);
        }
    }
}